<template>
  <div class="transfer-container">
    <div class="list-container">
      <div class="search-header">
        <div class="list-title">待选参数列表</div>
        <div class="search-controls">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索参数..."
            class="tech-input"
          />
          <div class="action-buttons">
            <button
              type="button"
              @click="selectAllAvailable"
              class="action-btn tech-btn"
              :class="{ 'tech-btn-active': isAllSelected }"
            >
              全选
            </button>
            <button
              type="button"
              @click="deselectAllAvailable"
              class="action-btn tech-btn-warn"
              :class="{ 'tech-btn-warn-active': isNoneSelected }"
            >
              全不选
            </button>
          </div>
        </div>
      </div>
      <div class="parameter-list">
        <div v-for="item in filteredParams" :key="item.value" class="parameter-item-container">
          <div class="parameter-item">
            <div class="parameter-item-content">
              <label class="tech-checkbox">
                <input
                  type="checkbox"
                  :value="item.value"
                  :checked="isChecked(item)"
                  :disabled="item.label === 'RecTime'"
                  @change="selectItem(item, 'available', $event)"
                />
                <span class="checkbox-custom"></span>
                <span class="checkbox-label">{{ item.label }}</span>
              </label>
      
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="list-container">
      <div class="search-header">
        <div class="list-title">已选参数列表</div>
        <input
          v-model="selectedSearchQuery"
          type="text"
          placeholder="搜索参数..."
          class="tech-input tech-input-complete"
        />
      </div>
      <div class="parameter-list">
        <div v-for="item in filteredSelectedParams" :key="item.value" class="parameter-item-container">
          <div class="parameter-item">
            <div class="parameter-item-content">
              <span class="checkbox-label">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, watch, nextTick} from 'vue'
import WithAPI from '@/views/parameter/parameter.api.ts'
import API from "@/views/playbackTask/playbackTask.api.ts";

interface Parameter {
  id: string;
  name: string;
  type?: string;
  children?: Parameter[];
}

interface SelectedItem {
  value: string;
  label: string;
  type: string;
  children?: SelectedItem[];
}

const props = defineProps<{
  parameters: Array<Parameter>,
}>()

// 展开的参数ID数组
const expandedItems = ref<Set<string>>(new Set())
// 已选参数列表的展开状态
const selectedExpandedItems = ref<Set<string>>(new Set())

const emit = defineEmits<{
  (e: 'update:selectedParams', value: Array<SelectedItem>): void
}>()

const searchQuery = ref('')
const selectedSearchQuery = ref('')

const isAllSelected = computed(() => selectedItems.value.available.length === availableParams.value.length && availableParams.value.length > 0)
const isNoneSelected = computed(() => selectedItems.value.available.length === 0)

async function getParamsList() {
  if (props.parameters) {
    let itemList: SelectedItem[] = [];
    props.parameters.forEach((item: Parameter) => {
      const newItem: SelectedItem = {
        value: item.id,
        label: item.name,
        type: item.type || '',
        // children: item.children?.map((child: Parameter) => ({
        //   value: child.id,
        //   label: child.name,
        //   type: child.type || '',
        //   children: child.children?.map((grandChild: Parameter) => ({
        //     value: grandChild.id,
        //     label: grandChild.name,
        //     type: grandChild.type || ''
        //   }))
        // }))
      };
      itemList.push(newItem);

      // 检查并添加已选参数到selectedItems.available
      const isSelected = selectedParams.value.some(param =>
        param.value === newItem.value ||
        (param.children && param.children.some(c => c.value === newItem.value))
      );
      if (isSelected && !selectedItems.value.available.includes(newItem.value)) {
        selectedItems.value.available.push(newItem.value);
      }

      // 检查子节点是否已选
      // if (newItem.children) {
      //   newItem.children.forEach((child: SelectedItem) => {
      //     const isChildSelected = selectedParams.value.some(param =>
      //       param.value === child.value ||
      //       (param.children && param.children.some(c => c.value === child.value))
      //     );
      //     if (isChildSelected && !selectedItems.value.available.includes(child.value)) {
      //       selectedItems.value.available.push(child.value);
      //     }
      //   });
      // }
    });
    originalParams.value = [...itemList];
    availableParams.value = itemList;
  }
}

const filteredSelectedParams = computed(() => {
  // 创建一个映射来存储所有已选参数
  const selectedMap = new Map(selectedParams.value.map(param => [param.value, param]))
  
  // 扁平化处理函数
  const flattenItems = (items: SelectedItem[]): SelectedItem[] => {
    return items.reduce((acc: SelectedItem[], item) => {
      if (selectedMap.has(item.value)) {
        acc.push({
          value: item.value,
          label: item.label,
          type: item.type
        })
      }
      
      // if (item.children && item.children.length > 0) {
      //   acc.push(...flattenItems(item.children))
      // }
      
      return acc
    }, [])
  }

  // 获取扁平化的已选参数列表
  const flattenedItems = flattenItems(availableParams.value)
  
  // 应用搜索过滤
  return flattenedItems.filter(item => {
    if (!item || typeof item !== 'object') return false
    return item.label && typeof item.label === 'string'
      ? item.label.toLowerCase().includes(selectedSearchQuery.value.toLowerCase())
      : false
  })
})
const originalParams = ref<SelectedItem[]>([])
const availableParams = ref<SelectedItem[]>([])
const filteredParams = computed(() => {
  const filterItem = (item: SelectedItem) => {
    if (!item || typeof item !== 'object') return false

    const matchesSearch = item.label && typeof item.label === 'string'
      ? item.label.toLowerCase().includes(searchQuery.value.toLowerCase())
      : false

    // if (item.children && Array.isArray(item.children) && item.children.length > 0) {
    //   const filteredChildren = item.children
    //     .filter((child: SelectedItem) => child && typeof child === 'object')
    //     .map((child: SelectedItem) => ({
    //       value: child.value,
    //       label: child.label,
    //       type: item.type,
    //       children: child.children
    //     }))
    //     .filter(child =>
    //       child && child.label && typeof child.label === 'string'
    //       ? child.label.toLowerCase().includes(searchQuery.value.toLowerCase())
    //       : false
    //     )

    //   if (filteredChildren.length > 0 || matchesSearch) {
    //     return {
    //       ...item,
    //       children: filteredChildren
    //     }
    //   }
    // }

    return matchesSearch
  }

  return availableParams.value
    .map((item: SelectedItem) => ({
      value: item.value,
      label: item.label,
      type: item.type,
      // children: item.children
    }))
    .filter(filterItem)
})

const selectedParams = ref<SelectedItem[]>([])
const selectedItems = ref<{
  available: string[];
  selected: string[];
}>({
  available: [],
  selected: []
})

// 判断是否选中
function isChecked(item: SelectedItem) {
  if (item.label === 'RecTime') return true
  return selectedItems.value.available.includes(item.value)
}

// 切换参数展开/折叠状态
const toggleExpand = (itemValue: string, isSelectedList: boolean = false) => {
  const targetSet = isSelectedList ? selectedExpandedItems : expandedItems
  if (targetSet.value.has(itemValue)) {
    targetSet.value.delete(itemValue)
  } else {
    targetSet.value.add(itemValue)
  }
}

const selectItem = (item: SelectedItem, type: 'available' | 'selected', event: Event) => {
  if (item.label === 'RecTime') return
  const checkbox = event.target as HTMLInputElement
  const checked = checkbox.checked
  const itemValue = item.value

  if (checked) {
    // 选中项
    if (!selectedItems.value[type].includes(itemValue)) {
      selectedItems.value[type].push(itemValue)

      // 自动添加到已选列表，保持与待选列表相同的顺序
      if (type === 'available') {
        // 找到当前项在待选列表中的索引
        const availableIndex = availableParams.value.findIndex(param => param.value === itemValue)
        if (availableIndex !== -1) {
          // 在已选列表中找到第一个索引大于当前项在待选列表中索引的位置
          const insertIndex = selectedParams.value.findIndex(param => {
            const paramIndex = availableParams.value.findIndex(p => p.value === param.value)
            return paramIndex > availableIndex
          })
          
          // 处理子节点
          let itemToAdd = { ...item }
          // if (item.children && item.children.length > 0) {
          //   // 对子节点进行排序
          //   itemToAdd.children = item.children
          //     .map(child => {
          //       const childIndex = availableParams.value[availableIndex].children?.findIndex(
          //         c => c.value === child.value
          //       )
          //       return { ...child, originalIndex: childIndex }
          //     })
          //     .sort((a, b) => {
          //       if (a.originalIndex === undefined) return 1
          //       if (b.originalIndex === undefined) return -1
          //       return a.originalIndex - b.originalIndex
          //     })
          //     .map(({ originalIndex, ...child }) => child)
          // }
          
          if (insertIndex === -1) {
            // 如果没有找到更大的索引，则添加到末尾
            selectedParams.value.push(itemToAdd)
          } else {
            // 在找到的位置插入
            selectedParams.value.splice(insertIndex, 0, itemToAdd)
          }
        } else {
          // 如果在待选列表中找不到，则添加到末尾
          selectedParams.value.push(item)
        }
        emit('update:selectedParams', selectedParams.value)
      }
    }
  } else {
    // 取消选中
    selectedItems.value[type] = selectedItems.value[type].filter((id: string) => id !== itemValue)

    // 自动从已选列表移除
    if (type === 'available') {
      selectedParams.value = selectedParams.value.filter(param => param.value !== itemValue)
      emit('update:selectedParams', selectedParams.value)
    }
  }
}

// 全选待选参数
const selectAllAvailable = () => {
  const allAvailableItems = getAllAvailableItems(availableParams.value)
  const recTimeId = getRecTimeId()
  selectedItems.value.available = Array.from(new Set([...allAvailableItems, recTimeId]))
  
  // 更新已选参数列表
  updateSelectedParamsFromAvailable()
}

// 全不选待选参数（RecTime始终保留）
const deselectAllAvailable = (e) => {
  const recTimeId = getRecTimeId()
  selectedItems.value.available = recTimeId ? [recTimeId] : []
  updateSelectedParamsFromAvailable()
  e.currentTarget.blur();
}

// 获取所有可用的参数项（包括子项）
const getAllAvailableItems = (items: SelectedItem[]): string[] => {
  const result: string[] = []
  items.forEach(item => {
    result.push(item.value)
    // if (item.children && item.children.length > 0) {
    //   result.push(...getAllAvailableItems(item.children))
    // }
  })
  return result
}

// 根据待选列表更新已选参数列表
const updateSelectedParamsFromAvailable = () => {
  const newSelectedParams: SelectedItem[] = []
  
  availableParams.value.forEach(item => {
    if (selectedItems.value.available.includes(item.value)) {
      newSelectedParams.push({ ...item })
    }
    
    // if (item.children && item.children.length > 0) {
    //   item.children.forEach(child => {
    //     if (selectedItems.value.available.includes(child.value)) {
    //       newSelectedParams.push({ ...child })
    //     }
    //   })
    // }
  })
  
  selectedParams.value = newSelectedParams
  emit('update:selectedParams', selectedParams.value)
}

// 添加 watch 来监听搜索查询的变化
watch([searchQuery, selectedSearchQuery], () => {
  // 当搜索查询变化时，确保已选参数保持不变
  emit('update:selectedParams', selectedParams.value)
})
watch(availableParams, ()=>{
  console.log("selectedItems.value.available.length====", selectedItems.value.available.length)
})

// 获取RecTime的id
function getRecTimeId() {
  const rec = availableParams.value.find(item => item.label === 'RecTime')
  return rec ? rec.value : ''
}

// 初始化默认选中RecTime
onMounted(() => {
  getParamsList();
  nextTick(() => {
    selectAllAvailable();
  });
})
</script>

<style scoped>
@import '../../../src/assets/css/theme.css';
@import '../../../src/assets/css/buttons.css';
@import '../../../src/assets/css/modal.css';
.transfer-container {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 20px;
  height: 100%;
}

.list-container {
  flex: 1;
  background: var(--table-body-bg-color);
  border-radius: 8px;
  border: 1px solid var(--modal-divide);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
  height: 500px;
}

.list-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  /*background: linear-gradient(90deg,*/
  /*  rgba(56, 189, 248, 0.3) 0%,*/
  /*  rgba(30, 64, 175, 0.6) 50%,*/
  /*  rgba(56, 189, 248, 0.3) 100%);*/
}

.search-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--modal-divide);
  /*background: rgba(255, 255, 255, 0.8);*/
}

.list-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 8px;
}

.search-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  white-space: nowrap;
}

.tech-input {
  flex: 1;
  padding: 8px 12px;
  font-size: 14px;
  border-radius: 4px;
    background: var(--select-background);
    color: var(--text-color);
    border: 1px solid var(--input-border-color);
  transition: all 0.2s ease;
}
.tech-input::placeholder {
  color: var(--preview-text-color);
}
.tech-input-complete {
  width: 100%;
}

.tech-input:focus {
  outline: none;
  border-color: rgba(30, 64, 175, 0.4);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.parameter-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 16px;
}

.parameter-item-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 2px;
}

.parameter-item {
  padding: 4px 0;
  transition: background-color 0.2s;
  border-radius: 4px;
}

.parameter-item:hover {
  background-color: var(--btn-hover-color);
}

.parameter-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tech-checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  position: relative;
  flex: 1;
}

.tech-checkbox input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkbox-custom {
  position: relative;
  height: 18px;
  width: 18px;
  min-width: 18px;
  border-radius: 4px;
  border: 1px solid var(--btn-click-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
}

.tech-checkbox input:checked ~ .checkbox-custom {
    color: var(--global-color-white);
    background-color: var(--ant-checkbox-checked);
    border-color: var(--btn-click-color);
}

.checkbox-custom:after {
  content: "";
  position: absolute;
  display: none;
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.tech-checkbox input:checked ~ .checkbox-custom:after {
  display: block;
}

.checkbox-label {
  color: var(--text-color);
  font-size: 14px;
}

.button-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  justify-content: center;
  padding: 0 10px;
  position: relative;
  transform: translateY(200%);
}

.button-container button {
  padding: 8px 16px;
  background: rgb(237, 243, 255);
  border: 1px solid rgb(196, 216, 255);
  color: #1e3a8a;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.button-container button:hover {
  background: rgb(224, 235, 255);
  border-color: rgb(165, 195, 255);
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 1024px) {
  .transfer-container {
    gap: 10px;
    padding: 10px;
  }
  .list-container {
    height: 400px;
  }
  .list-title {
    font-size: 14px;
  }
  .tech-input {
    font-size: 12px;
    padding: 6px 10px;
  }
  .checkbox-label {
    font-size: 12px;
  }
  .checkbox-custom {
    height: 16px;
    width: 16px;
    min-width: 16px;
  }
  .checkbox-custom:after {
    left: 5px;
    top: 1px;
    width: 4px;
    height: 8px;
  }
  .button-container button {
    font-size: 12px;
    padding: 6px 12px;
  }
}

</style>
